package com.tao.controller;

import com.tao.pojo.Result;
import com.tao.pojo.User;
import com.tao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //用户注册接口
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        User u = userService.findByUsername(user.getUsername());
        if (u == null){
            int i = userService.register(user);
            if (i == 1){
                return Result.success();
            }else {
                return Result.error("注册失败");
            }
        }else {
            return Result.error("用户名已被占用");
        }
    }

    //添加、更新用户接口
    @PostMapping("/save")
    public Result save(@RequestBody User user){
        if (user.getId() == null){
            User u = userService.findByUsername(user.getUsername());
            if (u == null){
                int i = userService.register(user);
                if (i == 1){
                    return Result.success();
                }else {
                    return Result.error("添加失败");
                }
            }else {
                return Result.error("用户名已被占用");
            }
        }else {
            int i = userService.update(user);
            if (i == 1){
                return Result.success();
            }else {
                return Result.error("更新失败");
            }
        }
    }

    //删除用户
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        int i = userService.delete(id);
        if (i == 1){
            return Result.success();
        }else {
            return Result.error("删除失败");
        }
    }

    @GetMapping("/selectPage")
    public Result<Map<String,Object>> findPage(@RequestParam Integer pageNum,
                                               @RequestParam Integer pageSize,
                                               @RequestParam String username){
        username = "%" + username + "%";
        pageNum = (pageNum - 1) * pageSize;
        List<User> list = userService.selectPage(pageNum,pageSize,username);
        Integer total = userService.selectTotal(username);
        Map<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("data",list);
        return Result.success(map);
    }
}
